/*
Copyright (c) 2007,2007 Elizeu Nogueira da R. Jr.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Elizeu Nogueira da R. Jr. nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This package is based on HypersonicSQL, originally developed by Thomas Mueller.
and HSQLDB original developed by the HSQL Development Group
*/

package br.com.dreamsource.mobile.jmesql;

import java.util.*;
import java.io.*;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;
import br.com.dreamsource.mobile.jmesql.exceptions.SQLException;
import br.com.dreamsource.mobile.jmesql.jdbcStatement;

public class jdbcConnection {
    
    public static int TRANSACTION_NONE	     = 0;
    public static int TRANSACTION_READ_UNCOMMITTED = 1;
    public static int TRANSACTION_READ_COMMITTED   = 2;
    public static int TRANSACTION_REPEATABLE_READ  = 4;
    public static int TRANSACTION_SERIALIZABLE     = 8;
    
    private boolean	     bClosed;
    private boolean	     bAutoCommit;
    private String	     sDatabaseName;
    private final static int HTTP = 0, STANDALONE = 1, INTERNAL = 2, HSQL = 3;
    private int		     iType;
    private Databases	 dDatabase;
    private Channel	     cChannel;
    HttpConnection          sSocket;
    DataOutputStream	 dOutput;
    DataInputStream	     dInput;
    public static final int DEFAULT_HSQL_PORT = 9001;

    private static Hashtable tDatabase = new Hashtable();
    private static Hashtable iUsageCount = new Hashtable();
    private String HttpURL;

    public jdbcStatement createStatement() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (bClosed) {
	    return null;
	}

	return new jdbcStatement(this);
    }

    public String nativeSQL(String sql) {
	if (sql.indexOf('{') == -1) {
	    return sql;
	}

	char    s[] = sql.toCharArray();
	boolean changed = false;
	int     state = 0;
	int     len = s.length;

	for (int i = 0; i < len; i++) {
	    char c = s[i];

	    switch (state) {

	    case 0:    // normal
		if (c == '\'') {
		    state = 1;
		} else if (c == '"') {
		    state = 2;
		} else if (c == '{') {
		    s[i] = ' ';
		    changed = true;

		    String sub = sql.substring(i + 1).toUpperCase();

		    if (sub.startsWith("?=")) {
			i += 2;
		    } else if (sub.startsWith("CALL")) {
			i += 4;
		    } else if (sub.startsWith("ESCAPE")) {
			i += 6;
		    }

		    state = 3;
		}

		break;

	    case 1:    // inside ' '

	    case 5:    // inside { } and ' '
		if (c == '\'') {
		    state -= 1;
		}

		break;

	    case 2:    // inside " "

	    case 6:    // inside { } and " "
		if (c == '"') {
		    state -= 2;
		}

		break;

	    case 3:    // inside { } before whitespace
		if (c == ' ') {
		    state = 4;
		} else {
		    s[i] = ' ';
		    changed = true;
		}

		break;

	    case 4:    // inside { } after whitespace
		if (c == '\'') {
		    state = 5;
		} else if (c == '"') {
		    state = 6;
		} else if (c == '}') {
		    s[i] = ' ';
		    changed = true;
		    state = 0;
		}
	    }
	}

	if (changed) {
	    sql = new String(s);

	    if (Trace.TRACE) {
		Trace.trace(s + " > " + sql);
	    }
	}

	return sql;
    }

    public void setAutoCommit(boolean autoCommit) throws SQLException {
	bAutoCommit = autoCommit;

	execute("SET AUTOCOMMIT " + (bAutoCommit ? "TRUE" : "FALSE"));
    }

    public boolean getAutoCommit() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return bAutoCommit;
    }

    public void commit() throws SQLException {
	execute("COMMIT");
    }

    public void rollback() throws SQLException {
	execute("ROLLBACK");
    }

    public void close() throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	if (bClosed) {
	    return;
	}

	if ((iType == STANDALONE) || (iType == INTERNAL)) {
	    closeStandalone();
	} else {
	    execute("DISCONNECT");
	}

	bClosed = true;
    }

    public boolean isClosed() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return bClosed;
    }

    public jdbcDatabaseMetaData getMetaData() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return new jdbcDatabaseMetaData(this);
    }

    public void setReadOnly(boolean readonly) throws SQLException {
	execute("SET READONLY " + (readonly ? "TRUE" : "FALSE"));
    }

    public boolean isReadOnly() throws SQLException {
	String    s =
	    "SELECT * FROM SYSTEM_CONNECTIONINFO WHERE KEY='READONLY'";
	jdbcResultSet r = execute(s);

	r.next();

	return r.getString(2).equals("TRUE");
    }

    public void setCatalog(String catalog) {
	if (Trace.TRACE) {
	    Trace.trace(catalog);
	}
    }

    public String getCatalog() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return null;
    }

    public void setTransactionIsolation(int level) {
	if (Trace.TRACE) {
	    Trace.trace(level);
	}
    }

    public int getTransactionIsolation() {
	if (Trace.TRACE) {
	    Trace.trace();
	}

	return TRANSACTION_READ_UNCOMMITTED;
    }

    public void clearWarnings() {
	if (Trace.TRACE) {
	    Trace.trace();
	}
    }

    public jdbcStatement createStatement(int type,
				     int concurrency) throws SQLException {
	return createStatement();
    }

    jdbcConnection(String s, String user,
		   String password) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace(s);
	}

	bAutoCommit = true;
	sDatabaseName = s;

        iType = STANDALONE;

        openStandalone(user, password);
    }
    

    jdbcConnection(Channel c) throws SQLException {
	iType = INTERNAL;
	cChannel = c;
	dDatabase = c.getDatabase();
    }

    jdbcResultSet execute(String s) throws SQLException {
	if (Trace.TRACE) {
	    Trace.trace(s);
	}

	Trace.check(!bClosed, Trace.CONNECTION_IS_CLOSED);

    return executeStandalone(s);

    }
    
    public jdbcPreparedStatement prepareStatement(String sql) {
	if (Trace.TRACE) {
	    Trace.trace(sql);
	}

	if (bClosed) {
	    return null;
	}

	return new jdbcPreparedStatement(this, sql);
    }    

    boolean usesLocalFiles() {

	// Standalone connections do, HTTP connections not
	return iType != HTTP;
    }

    String getName() {
	return sDatabaseName;
    }

    private String      sConnect, sUser, sPassword;
    final static String ENCODING = "8859_1";

    private synchronized jdbcResultSet executeHSQL(String s)
	    throws SQLException {
	byte result[];

	try {
	    dOutput.writeUTF(s);
	    dOutput.flush();

	    int len = dInput.readInt();

	    result = new byte[len];

	    int p = 0;

	    while (true) {
		int l = dInput.read(result, p, len);

		if (l == len) {
		    break;
		} else {
		    len -= l;
		    p += l;
		}
	    }
	} catch (Exception e) {
	    throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage());
	}

	return new jdbcResultSet(new Result(result));
    }

    private synchronized void openStandalone(String user, String password)
	    throws SQLException {
	dDatabase = (Databases) tDatabase.get(sDatabaseName);

	int usage;

	if (dDatabase == null) {
	    dDatabase = new Databases(sDatabaseName);

	    tDatabase.put(sDatabaseName, dDatabase);

	    usage = 1;
	} else {
	    usage = 1 + ((Integer) iUsageCount.get(sDatabaseName)).intValue();
	}

	iUsageCount.put(sDatabaseName, new Integer(usage));

	cChannel = dDatabase.connect(user, password);
    }

    public void jdbcFinalize() {
	try {
	    close();
	} catch (SQLException e) {}
    }

    private synchronized void closeStandalone() throws SQLException {
	Integer i = (Integer) iUsageCount.get(sDatabaseName);

	if (i == null) {

	    // It was already closed - ignore it.
	    return;
	}

	int usage = i.intValue() - 1;

	if (usage == 0) {
	    iUsageCount.remove(sDatabaseName);
	    tDatabase.remove(sDatabaseName);

	    if (!dDatabase.isShutdown()) {
		execute("SHUTDOWN");
	    }

	    dDatabase = null;
	    cChannel = null;
	} else {
	    iUsageCount.put(sDatabaseName, new Integer(usage));
	    execute("DISCONNECT");
	}
    }

    private jdbcResultSet executeStandalone(String s) throws SQLException {
	return new jdbcResultSet(dDatabase.execute(s, cChannel));
    }

}
